//
//  VideoListViewModel.swift
//  ios_swift_demo1
//
//  Created by liutao on 2020/7/17.
//  Copyright © 2020 lt. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import HandyJSON
import Moya
import MJRefresh
//0热门，1百变穿搭，2时尚潮男，3舒适好物，4美妆达人，5魅力配饰，6步履不停，7包罗万象，8萌娃驾到，9宝妈神器，10居家好物，11吃货专区，12数码达人，13用电能手，15伴你前行，16学习娱乐，17萌宠世界，14其他
//let catIDMap :[String: Int] = ["热门": 0, "百变穿搭": 1, "时尚潮男": 2, "舒适好物": 3, "美妆达人": 4, "魅力配饰": 5, "步履不停": 6, "包罗万象": 7, "萌娃驾到": 8, "宝妈神器": 9, "居家好物": 10, "吃货专区": 11, "数码达人": 12, "用电能手": 13, "伴你前行": 15, "学习娱乐": 16,"萌宠世界":17,"其他":14]

let catNameArray :[String] = ["热门", "百变穿搭", "时尚潮男", "舒适好物", "美妆达人", "魅力配饰", "步履不停", "包罗万象", "萌娃驾到", "宝妈神器", "居家好物", "吃货专区", "数码达人", "用电能手", "伴你前行", "学习娱乐","萌宠世界","其他"]

let catIDArray:[Int] = [ 0,  1, 2,  3,  4,  5,  6, 7,  8,  9,  10,  11,  12,  13,  15, 16,17,14]

class VideoListViewModel {
    var videoDataSource: BehaviorRelay<[VideoCellViewModel]> = BehaviorRelay(value: [])
    
    var dataSourceDriver: Driver<[VideoCellViewModel]> {
        return videoDataSource.asDriver().skip(1)
    }
    
    var dataSource: [VideoCellViewModel] {
        return videoDataSource.value
    }
    
    private var minId = 1
    
    var catId = 0
    
    func requestData(_ tableView:UITableView,isRefresh:Bool,callBackFuc:@escaping() -> Void) {
        print("catid----> \(catId)------>minId \(minId)")
      
        var postProvider = DYApiProvider
        if isRefresh {
            minId = 1
            postProvider = DYApiProviderAndLoading
        }
        let observable = postProvider.rx.request(.getTrillData(minId: minId,catId:catId)).map(Resource.self).asObservable()
        
        _ = observable.subscribe(onNext: {[weak self] (json)  in
            guard let `self` = self else {return}
            if(isRefresh){
                tableView.uHead.endRefreshing()
            }else{
                if(json.minId == 0){
                    tableView.uFoot.endRefreshingWithNoMoreData()
                }else{
                    tableView.uFoot.endRefreshing()
                }
            }
            print("json.minId---",json.minId ?? "","数据长度----> \(self.videoDataSource.value.count)")
            self.minId = json.minId ?? 1
            var newArray = self.videoDataSource.value
            if isRefresh {newArray.removeAll()}
            newArray.append(contentsOf:json.data.map({ (trillEntity) -> VideoCellViewModel in return VideoCellViewModel(trillEntity: trillEntity)}))
            self.videoDataSource.accept(newArray)
            callBackFuc()
            },onError: { (error) in
                isRefresh ? tableView.uHead.endRefreshing() : tableView.uFoot.endRefreshing()
                print(error)
            }
        )
    }
}
